import classNames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { changeTodoStatus, delTodo } from '../../store/actions/todo'
export default function TodoItem({ item }) {
  const inputRef = useRef(null)
  const dispatch = useDispatch()
  // 显示编辑框，准备一个变量用于控制编辑框的显示与否
  const [currentId, setCurrentId] = useState('')
  // 把当前双击的那一项的 item.id 给 currentId
  // 显示编辑框
  const handleDBLClick = (id) => setCurrentId(id)
  const handleTodoDel = (id) => dispatch(delTodo(id))
  const handleChangeStatus = (id) => dispatch(changeTodoStatus(id))
  // 离开 input 框的时候隐藏输入框
  const handleBlur = () => setCurrentId('')
  // 只有等 id 变化完毕之后才应该获取焦点比较合适，获取焦点
  useEffect(() => inputRef.current.focus(), [currentId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: item.id === currentId,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleChangeStatus(item.id)}
        />
        <label onDoubleClick={() => handleDBLClick(item.id)}>{item.name}</label>
        <button
          className='destroy'
          onClick={() => handleTodoDel(item.id)}
        ></button>
      </div>
      {/* 编辑功能 */}
      <input
        className='edit'
        value={`Create a TodoMVC template${item.id}`}
        onChange={() => {}}
        ref={inputRef}
        onBlur={handleBlur}
      />
    </li>
  )
}
